#include <iostream>
#include <unistd.h>
#include <cstdio>
#include <sys/types.h>
#include <sys/wait.h>

void Printpending(const sigset_t &pending)
{
    std::cout << "curr process[" << getpid() << "]pending";
    for (int i = 31; i >= 1; i--)
    {
        if (sigismember(&pending, i) == 1)
        {
            std::cout << "1";
        }
        else
        {
            std::cout << "0";
        }
    }

    std::cout<<std::endl;
}

void handler(int signum)
{
    std::cout << "第" << signum << "号信号被递达!" << std::endl;
    std::cout << "------------------------------------" << std::endl;
    sigset_t pending;
    Printpending(pending);
    std::cout << "------------------------------------" << std::endl;
}

int main()
{
    // Step1. 捕捉2号信号
    signal(2, handler);

    // Step2. 屏蔽2号信号
    sigset_t old_set, set;

    // 只是把用户级别的sigset_t置空，内核block没有置空。
    sigemptyset(&old_set);
    sigemptyset(&set);
    sigaddset(&set, 2);

    int ret = sigprocmask(SIG_BLOCK, &set, &old_set);

    int cnt = 15;
    while (true)
    {
        sigset_t pending;
        sigpending(&pending);

        cnt--;
        Printpending(pending);

        if (cnt == 0)
        {
            std::cout << "解除对2号信号的屏蔽!!!" << std::endl;
            sigprocmask(SIG_SETMASK, &old_set, &set);

            
        }

        sleep(1);
    }

    return 0;
}